//
//  HomeVC.m
//  Echo
//
//  Created by Cospring on 14/12/16.
//  Copyright (c) 2014年 sina. All rights reserved.
//

#import "HomeVC.h"
#import "ApiConfig.h"
#import "UIConfig.h"
#import "bottomCommentBar.h"
#import "Tweet.h"
#import "User.h"
#import "CurrentUser.h"
#import "Pic.h"
#import "TweetView.h"
#import "Comment.h"
#import "SVProgressHUD.h"

#import "SDWebImageManager.h"



@implementation HomeVC {
    UIScrollView *TweetScrollView;
    NSMutableArray *tweetViewArray;
    NSMutableArray *commentVCArray;
    CommentVC *commentVC;
    NavigationVC *navigationVC;
    
    UIBarButtonItem *leftBarButton;
    NSDictionary *TAG_NAME_HASH;
    
//    NSString *currentItem;
}

//var leftBtn = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
//leftBtn.frame = CGRectMake(0, 0, 25, 20)
//leftBtn.setTitleColor(UIColor.blueColor(), forState: .Normal)
//leftBtn.addTarget(self, action: "showLeftNavigation", forControlEvents: .TouchUpInside)
//leftBtn.setBackgroundImage(UIImage(named: "left_nav"), forState: .Normal)
//self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn)
//
//self.navigationItem.hidesBackButton = true

bool showLock = false;

- (void)showNavigation
{
//    self.navigationController.navigationBarHidden = YES;
    self.navigationController.navigationBar.alpha = 0.01;
//    [self.navigationController setNavigationBarHidden:YES animated:NO];
//    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
//    self.navigationController.navigationBar.translucent = YES;
    navigationVC.view.hidden = NO;
    [self.view bringSubviewToFront:navigationVC.view];
    
    
//    navigationVC = [[NavigationVC alloc] init];
//    navigationVC.view.frame = [[UIScreen mainScreen] bounds];
    
    //    CGRect rect = navigationVC.view.frame;
    //    rect.origin.y -= NAV_STATUS_HEIGHT;
    //    navigationVC.view.frame = rect;
    
//    navigationVC.delegate = self;
    
//    [self.navigationController presentViewController:navigationVC animated:YES completion:^{
//        
//    }];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSLog(@"%@", [CurrentUser SharedCurrentUser].token);
    TAG_NAME_HASH = @{
        @"Hadoop":      CATE_HADOOP,
        @"Java":        CATE_JAVA,
        @"PHP":         CATE_PHP,
        @"Javascript":  CATE_JAVASCRIPT,
        @"OC":          CATE_OC,
        @"Python":      CATE_PYTHON,
        @"C++":         CATE_CPP,
        @"Perl":        CATE_PERL,
        @"C":           CATE_C,
        @"R":           CATE_R,
        @"Swift":       CATE_SWIFT
    };
    
//    [CurrentUser tryLogin];
    
    
#pragma mark -- init navigationItem
    self.navigationItem.title = @"Java";
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 25, 20);
    [leftButton addTarget:self action:@selector(showNavigation) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"left_nav"] forState:UIControlStateNormal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.hidesBackButton = YES;
    
    
#pragma mark -- init TweetScrollView
    TweetScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    TweetScrollView.contentSize = CGSizeMake(SCREEN_WIDTH * 10, 0);
    TweetScrollView.userInteractionEnabled = YES;
//    TweetScrollView.delegate = self;
    TweetScrollView.bounces = YES;
    TweetScrollView.pagingEnabled = YES;
    TweetScrollView.showsHorizontalScrollIndicator = NO;
    TweetScrollView.showsVerticalScrollIndicator = NO;
    
    [self.view addSubview:TweetScrollView];
    
    
#pragma mark -- fetch tweet data
//    NSString *txt = @"【#2015放假安排# 公布：除夕放假】①元旦1月1日-3日放假调休，4日(星期日)上班②春节：2月18日(除夕)-24日放假调休 ②清明节：4月5日放假，6日(星期一)补休 ③劳动节：5月1日放假，与周末连休 ④端午节：6月20日-22日 ⑤中秋节：9月27日放假 ⑥国庆节：10月1日-7日放假，10月10日(星期六)上班。扩散!";
    
    
    UIColor *tipColor = [[UIColor alloc] initWithRed:0.4 green:0.4 blue:0.4 alpha:0.8];
    [SVProgressHUD setBackgroundColor:tipColor];
//    [SVProgressHUD showWithStatus:@"加载中..." maskType:SVProgressHUDMaskTypeClear];
    
    
//    [Tweet tweetsOfCate:CATE_JAVA WithBlock:^(NSArray *Tweets, NSError *error) {
//        //tweets里是Tweet的数组，在这里是你获取后的处理逻辑
//        NSLog(@"%lu", (unsigned long)[Tweets count]);
//        
//        NSUInteger count = [Tweets count];
//        if (error) {
//            NSLog(@"%@", error);
//            return;
//        }
//        
//        if (count <= 0) {
//            NSLog(@"加载失败");
//            return;
//        }
//        
//        if (count > 10) {
//            count = 10;
//        }
//        
//        tweetViewArray = [[NSMutableArray alloc] init];
//        commentVCArray = [[NSMutableArray alloc] initWithCapacity:count];
//        
//        Tweet *tweet = Tweets[0];
//        CGRect tweetViewRect = CGRectMake(TWEET_LEFT_MARGIN, 0, TWEET_FRAME_WIDTH, TWEET_VIEW_HEIGHT);
//        
//        TweetView *tweetView = [[TweetView alloc] initWithFrame:tweetViewRect tweet:tweet];
//        tweetView.commentDelegate = self;
//        tweetView.tweetScrollView.delegate = self;
//        
//        [tweetViewArray addObject:tweetView];
//        [TweetScrollView addSubview:tweetView];
//        
//        for (int i = 1; i < count; i++) {
//            Tweet *tweet = Tweets[i];
//            NSLog(@"%f", TWEET_LEFT_MARGIN + TWEET_FRAME_WIDTH*i);
//            CGRect tweetViewRect = CGRectMake(TWEET_LEFT_MARGIN + SCREEN_WIDTH * i, 0, TWEET_FRAME_WIDTH, TWEET_VIEW_HEIGHT);
//            
//            TweetView *tweetView = [[TweetView alloc] initWithFrame:tweetViewRect tweet:tweet];
//            tweetView.commentDelegate = self;
//            tweetView.tweetScrollView.delegate = self;
//            
//            [tweetViewArray addObject:tweetView];
//            [TweetScrollView addSubview:tweetView];
//        }
//        
//        [SVProgressHUD dismiss];
//        
//    }];
    
    
#pragma mark -- init navigationVC
    navigationVC = [[NavigationVC alloc] init];
    navigationVC.view.frame = [[UIScreen mainScreen] bounds];
    
//    CGRect rect = navigationVC.view.frame;
//    rect.origin.y -= NAV_STATUS_HEIGHT;
//    navigationVC.view.frame = rect;
    
    navigationVC.delegate = self;
    navigationVC.view.hidden = YES;
    [self addChildViewController:navigationVC];
    [self.view addSubview:navigationVC.view];
    
    
    CurrentUser *user = [CurrentUser SharedCurrentUser];
    NSLog(@"%@", user);
    
    if (user != nil) {
        NSURL *url = [[NSURL alloc] initWithString:user.avatar_url];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        navigationVC.userImage.image = image;
        navigationVC.userNameLabel.text = user.name;
        
    }
    
    
}

- (void)showCommentVC:(Tweet *)tweet
{
    NSLog(@"showCommentVC");
    
    leftBarButton = self.navigationItem.leftBarButtonItem;
    self.navigationItem.leftBarButtonItem = nil;
    
    if (![CurrentUser SharedCurrentUser].isLogin) {
        [CurrentUser tryLogin];
        return;
    }
    
    showLock = true;
    
//    if (commentVC != nil) {
//        [commentVC.view removeFromSuperview];
//        [commentVC removeFromParentViewController];
//        commentVC = nil;
//    }
    
    if (commentVC == nil) {
        commentVC = [[CommentVC alloc] init];
        
        commentVC.view.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
        commentVC.mid = tweet.mid;
//        commentVC.commentList = @[];
        
        commentVC.commentVCDelegate = self;
        [self addChildViewController:commentVC];
        [self.view addSubview:commentVC.view];
        
    } else {
        commentVC.mid = tweet.mid;
//        commentVC.commentList = @[];
        [commentVC.commentTableView reloadData];
    }
    
    [UIView animateWithDuration:0.5 animations:^{
        CGRect rect = TweetScrollView.frame;
        rect.origin.y = -SCREEN_HEIGHT;
        TweetScrollView.frame = rect;
        
        CGRect rect1 = commentVC.view.frame;
        rect1.origin.y = 64;
        commentVC.view.frame = rect1;
    } completion:^(BOOL finished) {
        showLock = false;
    }];
    
    
    if (![CurrentUser SharedCurrentUser].isLogin) {
        [CurrentUser tryLogin];
        return;
    }
    
    [Comment commentsOfTweet:tweet.mid AtPage:@1 WithBlock:^(NSArray *comments, NSError *error) {
        if (error) {
            NSLog(@"error = %@", error);
        }
        NSLog(@"comment return %@", comments);
        if (commentVC != nil) {
            commentVC.mid = tweet.mid;
            commentVC.commentList = comments;
            [commentVC.commentTableView reloadData];
        }
        
    }];
    
//    commentVC = [self.storyboard instantiateViewControllerWithIdentifier:@"CommentVC"];
    
}

- (void)scrollToTop
{
    showLock = true;
    self.navigationItem.leftBarButtonItem = leftBarButton;
    [UIView animateWithDuration:0.5 animations:^{
        CGRect rect = TweetScrollView.frame;
        rect.origin.y = 0;
        TweetScrollView.frame = rect;
        
        CGRect rect1 = commentVC.view.frame;
        rect1.origin.y = SCREEN_HEIGHT;
        commentVC.view.frame = rect1;
    } completion:^(BOOL finished) {
        showLock = false;
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSLog(@"%f", scrollView.contentOffset.y + scrollView.frame.size.height);
    if (scrollView.contentOffset.y + scrollView.frame.size.height > scrollView.contentSize.height + 120) {
        if (showLock == false) {
            
            int index = floor(TweetScrollView.contentOffset.x / SCREEN_WIDTH);
//            NSLog(@"%d", index);
//            NSLog(@"%@", tweetViewArray[index]);
            TweetView *tweetView = tweetViewArray[index];
            [self showCommentVC:tweetView.tweet];
            
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSLog(@"scrollViewDidEndDecelerating");
}


- (void)closeNavigation
{
//    [self.navigationController setNavigationBarHidden:NO animated:YES];
//    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    
    
    [UIView animateWithDuration:0.5 animations:^{
        navigationVC.view.layer.opacity = 0;
        self.navigationController.navigationBar.alpha = 1;
    } completion:^(BOOL finished) {
        
        navigationVC.view.hidden = YES;
        
//        self.navigationController.navigationBarHidden = NO;
        
        navigationVC.view.layer.opacity = 1;
    }];
    
}

- (void)selectItem:(NSString *)itemName
{
    NSLog(@"select: %@", itemName);
    if ([itemName isEqualToString:self.navigationItem.title]) {
        return;
    }
//    [SVProgressHUD showWithStatus:@"加载中..."];
//    UIColor *tipColor = [[UIColor alloc] initWithRed:0.6 green:0.6 blue:0.6 alpha:0.6];
    UIColor *tipColor = [[UIColor alloc] initWithRed:0.8 green:0.8 blue:0.8 alpha:1];
    [SVProgressHUD setBackgroundColor:tipColor];
    [SVProgressHUD showWithStatus:@"加载中..." maskType:SVProgressHUDMaskTypeClear];
    
    self.navigationController.navigationBarHidden = NO;
    navigationVC.view.hidden = YES;
    
    if (TAG_NAME_HASH[itemName] != nil) {
        [Tweet tweetsOfCate:TAG_NAME_HASH[itemName] WithBlock:^(NSArray *Tweets, NSError *error) {
            //tweets里是Tweet的数组，在这里是你获取后的处理逻辑
            NSLog(@"%lu", (unsigned long)[Tweets count]);
            self.navigationController.title = itemName;
            NSUInteger count = [Tweets count];
            if (count > 10) {
                count = 10;
            }
            
            for (int i = 0; i < count; i++) {
                Tweet *tweet = Tweets[i];
                TweetView *tweetView = tweetViewArray[i];
                if (tweetView != nil) {
                    [tweetView changeTweet:tweet];
//                    tweetView.tweetScrollView.delegate = self;
                    NSLog(@"%@", tweet.text);
                }
            }
            
//            TweetScrollView.contentOffset.x = 0;
//            [TweetScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
//            [TweetScrollView setContentOffset:CGPointMake(0, -NAV_STATUS_HEIGHT)];
            
            self.navigationItem.title = itemName;
            [SVProgressHUD dismiss];
        }];
    }
    
}

#pragma mark weibo app
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [WeiboSDK handleOpenURL:url delegate:self];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [WeiboSDK handleOpenURL:url delegate:self];
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        NSString *wbToken = [(WBAuthorizeResponse *)response accessToken];
        NSString *cuid = [(WBAuthorizeResponse *)response userID];
        if (cuid && wbToken) {
            //NSLog(@"token:%@", wbToken);
            [CurrentUser Login:cuid Token:wbToken];
            CurrentUser *user = [CurrentUser SharedCurrentUser];
            NSLog(@"%@", user);
            NSURL *url = [[NSURL alloc] initWithString:user.avatar_url];
            NSData *data = [NSData dataWithContentsOfURL:url];
            UIImage *image = [UIImage imageWithData:data];
            navigationVC.userImage.image = image;
        } else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:ERROR_TITLE_AUTH_FAILED message:ERROR_MSG_AUTH_FAILED delegate:nil cancelButtonTitle:ERROR_BTN_CANCEL_TITLE otherButtonTitles:nil, nil];
            [alert show];
        }
    }
}

- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{
    NSLog(@"recive weibo reqeust!!!");
    
    
    
}

@end















